/**
 * Created by zhangsong on 2019-05-08.
 */
import React, { Component, Fragment } from 'react';
import { Button, Table, Popconfirm, Tooltip, Modal, DatePicker, Icon } from 'antd';
import { formatMessage } from '@/utils/i18n';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Pagination, gender } from '@/constants/styleConfig';
import Authorized from '@/utils/Authorized';
import { ContractorApplication } from '@/constants/routes';
import ContractorReducer from '@/dva/application/contractor';
import PDF from '@/components/PDFPreview';
import Power from '@/constants/power';
import ReaderCard from '@/components/ReaderCard/contractorIndex';
import ReaderCardIc from '@/components/ReaderCard/contractorIndexIc';
import moment from 'moment';
import _ from 'lodash';
// import { downloadCsv } from '@/utils/download/downloadCsv';


import Search from './search';

const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/c/font_3604216_kag2bfyte9s.js',
});

const { Namespace, Effects } = ContractorReducer;

@connect(
  state => ({
    contractorStore: state[Namespace],
  }),
  dispatch => ({
    handleQuery: data =>
      dispatch({
        type: `${Namespace}/${Effects.listByParam}`,
        data,
      }),
    removeById: data =>
      dispatch({
        type: `${Namespace}/${Effects.removeById}`,
        data,
      }),
    getPreviewPdfById: id =>
      dispatch({
        type: `${Namespace}/${Effects.getPreviewPdfById}`,
        data: {
          id,
        },
      }),
    handPDFModalCancel: () =>
      dispatch({
        type: `${Namespace}/${Effects.handPDFModalCancel}`,
        data: {},
      }),
    handleApproval: data =>
      dispatch({
        type: `${Namespace}/${Effects.approval}`,
        data,
      }),
    handleDisapproval: data =>
      dispatch({
        type: `${Namespace}/${Effects.disapproval}`,
        data,
      }),
    downLoadXlsx: () =>
      dispatch({
        type: `${Namespace}/${Effects.downLoadXlsx}`,
        data: {},
      }),
    openCallModal: data =>
      dispatch({
        type: `${Namespace}/${Effects.openCallModal}`,
        data,
      }),
    updateCallDate: data =>
      dispatch({
        type: `${Namespace}/${Effects.updateCallDate}`,
        data,
      }),
  }),
)
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      readerCardModal: false,
      record: null,
      calldate: undefined,
      newdata: new Date(new Date().getTime() - 24 * 60 * 60 * 1000),
      messdate: null,
      readerIcCardModal: false,
    };
  }

  componentDidMount() {
    const { handleQuery } = this.props;
    handleQuery({});
  }

  openRegisterEface = record => {
    this.setState({
      readerCardModal: true,
      record,
    });
  };

  openRegisterEfaceIc = record => {
    this.setState({
      readerIcCardModal: true,
      record,
    });
  };


  onDownload = listData => {
    // downloadCsv()
    // const array = listData.map(({ surname, nameAlias }) => [surname, nameAlias])
    // downloadCsv(array, ['name', 'age'], 'test.xlsx');
    const { downLoadXlsx } = this.props;
    downLoadXlsx();
    console.log('guolaiaiuiaia', listData);
  };

  closeRegisterEface = () => {
    this.setState({
      readerCardModal: false,
      record: null,
      readerIcCardModal: false,
    });
  };

  submitRegisterCard = () => {
    const { handleQuery } = this.props;
    this.setState({
      readerCardModal: false,
      record: null,
      readerIcCardModal: false,
    });
    handleQuery();
  };

  onDetailClick = (text, record) => {
    const { history } = this.props;
    const { id } = record;
    history.push(`${ContractorApplication.detail.url}?id=${id}`);
  };

  handleUpdate = (text, record) => {
    const { history } = this.props;
    const { id } = record;
    history.push(`${ContractorApplication.modify.url}?id=${id}`);
  };

  onPreviewClick = (text, record) => {
    const { getPreviewPdfById } = this.props;
    const { id } = record;
    getPreviewPdfById(id);
  };

  onPreviewClickSure = () => {
    const { handPDFModalCancel } = this.props;
    handPDFModalCancel();
  };

  openCancellAtion = item => {
    console.log('openCancellAtion', item, item.checked_expiry);
    const { openCallModal } = this.props;
    this.setState({
      calldate: item.checked_expiry,
      messdate: item,
      newdata: new Date(new Date().getTime() - 24 * 60 * 60 * 1000),
    })
    openCallModal(true);
  }

  renderColumns = () => [
    {
      title: formatMessage('applicationContractor.columns.headPhoto.name'),
      key: 'photograph_url',
      render: (text, record, index) => {
        return (
          <div>
            <img
              alt={formatMessage(
                'applicationContractor.columns.headPhoto.name',
              )}
              src={
                record.headPhoto
              }
              width={104}
              height={104}
            />
          </div>
        );
      },
    },
    {
      title: formatMessage({ id: 'applicationContractor.columns.surname.name' }),
      dataIndex: 'surname',
    },
    {
      title: formatMessage('applicationContractor.columns.nameAlias.name'),
      dataIndex: 'nameAlias',
    },
    {
      title: formatMessage('applicationContractor.columns.sex.name'),
      dataIndex: 'sex',
      render: text => (gender[text] ? formatMessage({ id: `baseInfo.${gender[text]}` }) : null),
    },
    {
      title: formatMessage('applicationContractor.columns.identityCard.name'),
      dataIndex: 'identityCard',
    },
    {
      title: formatMessage('applicationContractor.columns.birthday.name'),
      dataIndex: 'birthday',
    },
    // {
    //   title: formatMessage('applicationContractor.columns.placeOfBirth.name'),
    //   dataIndex: 'placeOfBirth',
    // },
    {
      title: formatMessage('applicationContractor.columns.telephone.name'),
      dataIndex: 'telephone',
    },
    {
      title: formatMessage('applicationContractor.columns.emergencyContactedName.name'),
      dataIndex: 'emergencyContactedName',
    },
    {
      title: formatMessage('applicationContractor.columns.contractNumber.name'),
      dataIndex: 'contract_number',
    },
    {
      title: formatMessage('applicationContractor.columns.checkedSpecified.name'),
      dataIndex: 'checked_specified',
    },
    {
      title: formatMessage('baseInfo.approvalStatusName'),
      dataIndex: 'checked_approved',
      render: text => {
        if (text === 1) {
          return formatMessage('applicationStaff.columns.checkedApproved.approved');
        }
        if (text === -1) {
          return formatMessage('applicationStaff.columns.checkedApproved.disapproved');
        }
        if (text === 3) {
          return formatMessage('applicationContractor.temporary.cancelled');
        }
        if (text === 0) {
          return formatMessage('baseInfo.needApprovalStatus');
        }
        return null;
      },
    },
    {
      title: formatMessage('applicationCommon.readerCard.passno'),
      dataIndex: 'card_no',
    },
    {
      title: formatMessage('applicationCommon.readerCard.status.name'),
      dataIndex: 'efaceStatus',
      render: text => formatMessage(`applicationCommon.readerCard.status.${text}`),
    },
    {
      title: formatMessage('baseInfo.updateTime'),
      dataIndex: 'updateTime',
    },
    {
      title: formatMessage('button.operator'),
      key: 'operator',
      render: (text, record, index) => {
        const { contractorStore, removeById } = this.props;
        const onUpdateClick = () => {
          this.handleUpdate(text, record, index);
        };
        const onDeleteClick = () => {
          removeById({
            id: record.id,
            page: contractorStore.page,
            pageSize: contractorStore.pageSize,
            query: contractorStore.query,
          });
        };
        const onDetailClick = () => {
          this.onDetailClick(text, record, index);
        };
        // const onApprovalClick = () => {
        //   handleApproval({
        //     id: text,
        //     page: contractorStore.page,
        //     pageSize: contractorStore.pageSize,
        //     query: contractorStore.query,
        //   });
        // };
        // const onDisapprovalClick = () => {
        //   handleDisapproval({
        //     id: text,
        //     page: contractorStore.page,
        //     pageSize: contractorStore.pageSize,
        //     query: contractorStore.query,
        //   });
        // };
        const onPreviewClick = () => {
          this.onPreviewClick(text, record, index);
        };
        return (
          <div>
            <Authorized authority={Power.ContractorApplication.detail}>
              <Tooltip title={formatMessage('button.detail')}>
                <Button
                  className="recovery"
                  htmlType="button"
                  size="small"
                  onClick={onDetailClick}
                  icon="eye"
                />
              </Tooltip>
            </Authorized>
            <Authorized authority={Power.ContractorApplication.printing}>
              <Button
                htmlType="button"
                type="dashed"
                size="small"
                onClick={() => this.openRegisterEface(record)}
              >
                {formatMessage('applicationCommon.readerCard.buttonName')}
              </Button>
            </Authorized>
            <Authorized authority={Power.ContractorApplication.modify}>
              <Tooltip title={formatMessage('button.update')}>
                <Button
                  className="recovery"
                  htmlType="button"
                  type="dashed"
                  size="small"
                  onClick={onUpdateClick}
                  icon="edit"
                />
              </Tooltip>
            </Authorized>
            {record.status === 0 ? (
              <Fragment>
                <Authorized authority={Power.ContractorApplication.remove}>
                  <Popconfirm
                    title={formatMessage({ id: 'baseInfo.askDeleteRecord' })}
                    onConfirm={onDeleteClick}
                    okText={formatMessage({ id: 'button.sure' })}
                    cancelText={formatMessage({ id: 'button.cancel' })}
                  >
                    <Tooltip title={formatMessage('button.remove')}>
                      <Button htmlType="button" type="danger" size="small" href="#" icon="delete" />
                    </Tooltip>
                  </Popconfirm>
                </Authorized>
              </Fragment>
            ) : null}
            <Authorized authority={Power.ContractorApplication.preview}>
              <Tooltip title={formatMessage('button.preview')}>
                <Button htmlType="button" size="small" onClick={onPreviewClick} icon="file-pdf" />
              </Tooltip>
            </Authorized>
            <Authorized authority={Power.ContractorApplication.cancellation}>
              <Button
                htmlType="button"
                type="dashed"
                size="small"
                onClick={() => this.openCancellAtion(record)}
              >
                {formatMessage('applicationCommon.readerCard.cancellAtion')}
              </Button>
            </Authorized>
            <Authorized authority={Power.StaffApplication.modifyic}>
              <Button
                htmlType="button"
                type="dashed"
                size="small"
                onClick={() => this.openRegisterEfaceIc(record)}
              >
                <IconFont type="icon-nfc" />
              </Button>
              {/* <Button
                className="recovery"
                htmlType="button"
                type="dashed"
                size="small"
                onClick={onUpdateClick}
                icon="material-design-icons"
              /> */}
            </Authorized>
            {/* <Authorized authority={Power.ContractorApplication.approval}> */}
            {/*  <Popconfirm */}
            {/*    title={formatMessage('baseInfo.disapproval')} */}
            {/*    onConfirm={onDisapprovalClick} */}
            {/*    okText={formatMessage('button.sure')} */}
            {/*    cancelText={formatMessage('button.cancel')} */}
            {/*  > */}
            {/*    <Tooltip title={formatMessage('button.disapproval')}> */}
            {/*      <Button type="danger" icon="stop" size="small" /> */}
            {/*    </Tooltip> */}
            {/*  </Popconfirm> */}
            {/*  <Popconfirm */}
            {/*    title={formatMessage('baseInfo.approval')} */}
            {/*    onConfirm={onApprovalClick} */}
            {/*    okText={formatMessage('button.sure')} */}
            {/*    cancelText={formatMessage('button.cancel')} */}
            {/*  > */}
            {/*    <Tooltip title={formatMessage('button.approval')}> */}
            {/*      <Button type="primary" icon="check-circle" size="small" /> */}
            {/*    </Tooltip> */}
            {/*  </Popconfirm> */}
            {/* </Authorized> */}
          </div>
        );
      },
    },
  ];

  onChange = pagination => {
    const { current, pageSize } = pagination;
    const { handleQuery, contractorStore } = this.props;
    const { query } = contractorStore;
    handleQuery({
      query,
      page: current,
      pageSize,
    });
  };

  onCallDate = (date, dateString) => {
    console.log('date, dateString', date, dateString);
    this.setState({
      newdata: dateString == null ? undefined : dateString,
    })
  }

  onOkDate = () => {
    const { messdate, newdata } = this.state;
    const { updateCallDate, contractorStore } = this.props;
    if (!newdata) {
      return
    }
    const data = {
      update: {
        surname: _.get(messdate, 'surname', null),
        id: messdate.id,
        pass_numbered: _.get(messdate, 'pass_numbered', null),
        checked_expiry: newdata,
      },
      pagesize: {
        page: contractorStore.page,
        pageSize: contractorStore.pageSize,
      },
    }
    console.log('看看這個時間', newdata);
    updateCallDate(data)
  }

  render() {
    const { contractorStore = {}, openCallModal } = this.props;
    const {
      pageSize,
      page,
      listData,
      total,
      listLoading,
      pdfLoading,
      pdfReview,
      pdfPreviewVisible,
      callMadal,
      xslloading,
    } = contractorStore;
    const { readerCardModal, record, calldate, readerIcCardModal, newdata } = this.state;

    const defvalue = newdata ? moment(newdata, 'YYYY-MM-DD') : undefined;
    const newdefvalue = calldate ? moment(calldate).format('YYYY-MM-DD') : undefined;
    const pagination = Pagination({
      page,
      pageSize,
      total,
    });
    return (
      <PageHeaderWrapper>
        <Search exloading={xslloading} onDownload={() => this.onDownload(listData)} />
        <Modal
          title={formatMessage('applicationCommon.readerCard.cancellAtion')}
          visible={callMadal}
          onCancel={() => {
            openCallModal(false);
          }}
          onOk={this.onOkDate}
        >
          <div>
            <div style={{ marginBottom: '10px' }}>
              <span style={{ marginRight: 10 }}>{`${formatMessage('applicationCommon.readerCard.donecancellAtionDate')}:`}</span>
              <span style={{ marginRight: 10 }}>{`${newdefvalue}`}</span>
            </div>
            <span style={{ marginRight: 10 }}>{`${formatMessage('applicationCommon.readerCard.modifycancellAtionDate')}:`}</span>
            <DatePicker value={defvalue} onChange={this.onCallDate} />
            {
              !newdata ? (
                <span style={{ marginLeft: 10, color: 'red' }}>請選擇</span>
              ) : null
            }

          </div>
        </Modal>
        {readerCardModal ? (
          <ReaderCard
            record={record}
            cancel={this.closeRegisterEface}
            sure={this.submitRegisterCard}
          />
        ) : null}

        {readerIcCardModal ? (
          <ReaderCardIc
            record={record}
            cancel={this.closeRegisterEface}
            sure={this.submitRegisterCard}
          />
        ) : null}
        <Table
          loading={!!listLoading}
          rowKey="id"
          columns={this.renderColumns()}
          dataSource={listData}
          onChange={this.onChange}
          pagination={pagination}
        />
        <PDF
          visible={pdfPreviewVisible}
          url={pdfReview}
          loading={pdfLoading}
          printing={Authorized.check(Power.ContractorApplication.printing, true, false)}
          onOk={() => this.onPreviewClickSure()}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Index;
